package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.ContractNumberGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.IDCardUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private BedMapper bedMapper;


    /**
     * 查询入住信息
     *
     * @param id 入住信息主键
     * @return 入住信息
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住信息列表
     *
     * @param checkIn 入住信息
     * @return 入住信息
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住信息
     *
     * @param ids 需要删除的入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息信息
     *
     * @param id 入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional
    public boolean apply(CheckInApplyDto dto) {
        // 1. 校验老人是否已入住
        // 1.1 查询老人信息 (根据身份证号)
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo()));
        // 1.2 已入住则抛异常显示该老人已入住
        if (elder != null) {
            if (elder.getStatus() == 1) {
                throw new RuntimeException("该老人已入住!");
            }
        }

        // 2. 更新床位状态为已入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        // 3. 新增或更新老人表
        Elder newElder = saveOrUpdateElder(dto, bed);
        // 4. 新增合同表
        saveContract(dto, newElder);
        // 5. 新增入住表
        CheckIn checkIn = saveCheckIn(dto, newElder);
        // 6. 新增入住配置表
        saveCheckInConfig(dto,checkIn);
        
        return true;
    }

    @Override
    public CheckInDetailVo getDetailById(Long id) {
        // 构建结果对象
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        // 查询入住信息
        CheckIn checkIn = this.getById(id);
        // 查询老人信息 构建checkInElderVo
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getId, checkIn.getElderId()));

        CheckInElderVo checkInElderVo = new CheckInElderVo();

        BeanUtils.copyProperties(elder, checkInElderVo);
        String idCardNo = elder.getIdCardNo();
        checkInElderVo.setAge(IDCardUtils.getAgeByIdCard(idCardNo));

        // 查询合同
        // 这里有问题,一个老人可能不止一个合同
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId, elder.getId()));

        // 查询入住配置 构建checkInConfigVo
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers
                .<CheckInConfig>lambdaQuery()
                .eq(CheckInConfig::getCheckInId, checkIn.getId()));

        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());

        // 转换家属列表 jsonstring->object(List<ElderFamilyVo>)
        String remark = elder.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSONObject.parseObject(remark, List.class);

        // 整合数据返回
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);

        return checkInDetailVo;
    }

    /**
     * 抽取出来的私有方法,保存入住配置表
     *
     * @param dto
     */
    private void saveCheckInConfig(CheckInApplyDto dto, CheckIn checkIn) {
        // 构造执行sql使用的对象
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setFeeStartDate(dto.getCheckInConfigDto().getStartDate());
        checkInConfig.setFeeEndDate(dto.getCheckInConfigDto().getEndDate());

        // 执行sql
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 抽取出来的私有方法,保存入住信息表
     *
     * @param dto
     */
    private CheckIn saveCheckIn(CheckInApplyDto dto, Elder elder) {
        // 构造执行sql使用的对象
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0L); // 0-已入住 1-已退住

        // 执行sql
        this.save(checkIn);
        return checkIn;
    }

    /**
     * 抽取出来的私有方法,保存合同表
     *
     * @param dto
     */

    private void saveContract(CheckInApplyDto dto, Elder elder) {
        // 构造执行sql使用的对象
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);

        contract.setElderId(Integer.parseInt(elder.getId().toString()));
        contract.setElderName(elder.getName());
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contract.setSignDate(LocalDateTime.now());
        contract.setContractNumber("HT"+ContractNumberGenerator.generateContractNumber());
//        boolean flag = startDate.isBefore(LocalDateTime.now());
//        contract.setStatus(flag?0:1);
        contract.setStatus(1);

        // 执行sql
        contractMapper.insert(contract);
    }

    /**
     * 抽取出来的私有方法,保存或更新老人表
     *
     * @param dto
     */
    private Elder saveOrUpdateElder(CheckInApplyDto dto, Bed bed) {
        // 从前端发的信息封装用于更新/新增的老人对象
        Elder newElder = new Elder();
        BeanUtils.copyProperties(dto.getCheckInElderDto(), newElder);
        newElder.setStatus(1);
        newElder.setBedId(bed.getId());
        newElder.setBedNumber(bed.getBedNumber());
        // object(List<ElderFamilyDto>) -> jsonstring
        newElder.setRemark(JSONObject.toJSONString(dto.getElderFamilyDtoList()));

        Elder oldElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .ne(Elder::getStatus, 1));// 状态不为1(不为已入住)
        // 判断老人信息是否已存在
        if (oldElder != null) {
            // 更新老人表
            elderMapper.updateById(newElder);
        } else {
            // 新增老人表
            elderMapper.insert(newElder);
        }

        return newElder;
    }
}
